<?php namespace Common\Model;
use Hdphp\Model\Model;
/**
 * 分类管理模型
 */
class Category extends Model
{
	//操作数据表
	protected $table = "category";
	//自动验证
	protected $validate = array(
		array("cname","required","分类名称不能为空",3,3),
		array("cname","maxlen:10","分类名称不能超过10个字符",3,3),
		array("csort","num:1,123456","分类排序必须为数字",3,3),
	);
	/**
	 * 添加
	 */
	public function store()
	{
		//自动验证
		if(!$this->create()) return false;
		//执行添加
		return $this->add();
	}
	/*
	 *  获得自己以及自己子级的数据
	 */
	 public function getCataData($cid)
	 {
//	 	p($this->get());
	 	$cids = $this -> getSon($this->get(), $cid);
		$cids[] = $cid;
		$cids = implode(',', $cids);
//		p($cids);
		//获得不是自己以及自己子级的数据
		$data = $this->where("cid not in ($cids)")->get();
//		p($data);
		//变成树状结构
		return Data::tree($data,'cname');
//		return $data['cname'];
	 }
	 public function getSon($data,$cid)
	{
		//设置一个静态，防止结果被覆盖
		static $temp = array();
		//循环数据
		foreach ($data as $k => $v) {
			//判断数据的pid等于cid，人后存入静态里面
			if($cid==$v['pid'])
			{
				$temp[] = $v['cid'];
				//递归调用函数
				$this -> getSon($data, $v['cid']);
			}
		}
		return $temp;
	}
	public function edit()
	{
		if(!$this->create()) return false;
		
		return $this -> save();
	}
	public function del($cid)
	{
		$pid = $this->where('cid',$cid) ->pluck('pid');
//		p($pid);
		$this->where('pid',$cid)->update(array('pid'=>$pid));
		$this -> where('cid',$cid) ->delete();
	}
}